import { login, getUserInfo, getUserDetail } from '@/api/user'
import { setToken, getToken, removeToken, setTimeToken } from '@/utils/auth'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  logout(state) {
    removeToken()
    state.token = null
    state.userInfo = {}
  }
}
const actions = {
  async login(context, payload) {
    try {
      const res = await login(payload)
      setTimeToken()
      context.commit('setToken', res)
    } catch (error) {
      console.log(error)
    }
  },
  async getUserInfo(context) {
    try {
      const res = await getUserInfo()
      const userInfo = await getUserDetail(res.userId)
      context.commit('setUserInfo', { ...res, ...userInfo })
    } catch (error) {
      console.log(error)
    }
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

